﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Amba.DownloadsCounter.Models;
using Amba.DownloadsCounter.ViewModels.Admin;
using Orchard.Data;
using Orchard.UI.Admin;

namespace Amba.DownloadsCounter.Controllers
{
    [Admin]
    public class AdminController : Controller
    {
        private IRepository<DownloadLogRecord> _downloadLogRecordRepo { get; set; }

        public AdminController(IRepository<DownloadLogRecord> downloadLogRecordRepo)
        {
            _downloadLogRecordRepo = downloadLogRecordRepo;
        }

        public ActionResult ByFile()
        {
            var result = new List<ByFileViewModel>();
            var urls = _downloadLogRecordRepo.Table.Select(x => x.Url).Distinct();
            //because of problem with group by in Orchard 1.6
            foreach (var url in urls)
            {
                var query = _downloadLogRecordRepo.Table.Where(x => x.Url == url);
                result.Add(new ByFileViewModel()
                    {
                        Url = url,
                        Count = query.Count(),
                        LastDownload = query.Max(x => x.LogDate)
                    });
            }
            return View(result);
        }

        public ActionResult Last100()
        {
            var list = _downloadLogRecordRepo.Table.OrderByDescending(x => x.LogDate).Take(100).ToList();
            return View(list);
        }

        public ActionResult ResetCounter(string url)
        {
            var logItems = _downloadLogRecordRepo.Table.Where(x => x.Url == url).ToList();
            foreach (var downloadLogRecord in logItems)
            {
                _downloadLogRecordRepo.Delete(downloadLogRecord);
            }
            return Content("0");
           
        }
    }

    
}